<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="value" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <el-progress v-if="showProgress" type="line" :percentage="percent" class="progress" />
    </el-upload>
  </div>
</template>

<script>
var COS = require('cos-js-sdk-v5')

// SECRETID 和 SECRETKEY请登录 https://console.cloud.tencent.com/cam/capi 进行查看和管理
var cos = new COS({
  SecretId: 'AKIDSn02sX3PYVK0TDtRnwscA7RZUEk3A66y',
  SecretKey: 'h9LJ3c3JQLyPdfU9ez84A7rTvTr4AB2g'
})
export default {
  props: {
    value: {
      type: String,
      require: true
    }
  },
  data() {
    return {
      imageUrl: '',
      percent: 0, // 上传进度
      showProgress: false // 是否展示进度条
    }
  },
  methods: {
    upload({ file }) {
      this.showProgress = true
      console.log(file)

      cos.uploadFile({
        Bucket: 'web87-1316386557', /* 填写自己的bucket，必须字段 */
        Region: 'ap-chongqing', /* 存储桶所在地域，必须字段 */
        Key: file.name, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = (progressData.loaded / progressData.total) * 100
        }
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          this.showProgress = false
          this.$emit('input', `https://${data.Location}`)
          console.log('上传成功', this.value)
        }
      })
    },
    handleAvatarSuccess(res, file) {
      console.log(file, 2222)
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG) {
        this.$message.error('上传头像图片只能是 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isPNG && isLt2M
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
